<template>
    <div class="common-layout">
        <el-container>
            <el-header height="75px">
                <head-page></head-page>
            </el-header>
            <el-main style="margin-top: -43px">
                <div>
                    <el-row class="input">
                        <el-col :span="12" style="margin-left: 6%; padding-top: 5px; padding-bottom: 5px">
                            <el-input
                                v-model="input"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                                maxlength="100"
                                show-word-limit
                                type="textarea"
                                placeholder="请输入关键词"
                            >
                            </el-input>
                        </el-col>
                        <el-col :span="10" style="margin-left: 15px">
                            <div style="width: 55%">
                                <el-cascader :options='provinceAndCityData' v-model='selectedOptions' @change='handleChange'></el-cascader>
                            </div>
                        </el-col>
                        <el-col :span="1" style="margin-left: -17%">
                            <el-button type="warning" :icon="Search" @click="search()">搜 索</el-button>
                        </el-col>
                        <el-col :span="2" style="margin-left: 4%">
                            <el-button type="danger" :icon="HomeFilled" @click="back()">主 页</el-button>
                        </el-col>
                    </el-row>
                    <el-container style="margin-top: 1%">
                        <el-aside width="200px" class="radius">
                            <el-row style="background-color: #738080;">
                                <el-col :span="7" class="title">
                                    <el-link size="large" style="margin-top: 2%;color: #FFFFFF; font-size: 22px; margin-left: -100px" @click="select">高级搜索</el-link>
                                </el-col>
                                <el-col :span="7" >
                                    <el-link style="color: #cecece;margin-top: 20%;margin-left: 10%;" @click="clear()">清除所有条件</el-link>
                                </el-col>
                            </el-row>
                            <br>
                            <el-text style="margin-left: -55%; font-size: 16px;padding: 2px">律师基本信息</el-text><br>
                            <el-input
                                v-model="professionalField"
                                :autosize="{ minRows: 2, maxRows: 4 }"
                                maxlength="100"
                                show-word-limit
                                type="textarea"
                                placeholder="请输入律师工作领域"
                                style="width: 80%; margin-top: 3%"
                            >
                            </el-input>
                            <el-cascader :options='provinceAndCityData' v-model='selectedOptions2' :placeholder="inform"
                                         @change='handleChange2' style="margin-top: 3%;margin-left: -28%"></el-cascader>
                            <el-input v-model="lawyerName" placeholder="请输入与律师姓名相关内容" clearable
                                      style="padding-top: 3%;width: 80%"/>

                            <el-divider></el-divider>
                            <el-text style="margin-left: -45%; font-size: 16px;padding: 2px">律师已帮助用户数目</el-text><br>
                            <el-row style="padding-top: 10px;">
                                <el-input v-model="value[0]" placeholder="自定义最小值" clearable
                                          style="padding-top: 2%;width: 30%; margin-left: 18%"/>
                                <el-text style="padding: 10px"> - </el-text>
                                <el-input v-model="value[1]" placeholder="自定义最大值" clearable
                                          style="padding-top: 2%;width: 30%"/>
                            </el-row>
                            <el-row  style="padding-top: 10px;">
                                <el-col :span="7" style="margin-left: 10%">
                                    <el-text>最小值  {{value[0]}}</el-text>
                                </el-col>
                                <el-col :span="12" ><el-text style="margin-left: 20%">最大值  {{value[1]}}</el-text></el-col>
                            </el-row>
                            <el-divider></el-divider>
                            <el-text style="margin-left: -55%; font-size: 16px;padding: 2px">律师其他信息</el-text><br>
                            <el-input v-model="position" placeholder="请输入与律师职位相关内容" clearable
                                      style="padding-top: 2%;width: 80%"/>
                            <el-input
                                v-model="lawyerIntroduction"
                                :autosize="{ minRows: 1, maxRows: 4 }"
                                maxlength="100"
                                show-word-limit
                                type="textarea"
                                placeholder="请输入律师相关信息方便查询"
                                style="width: 80%; margin-top: 3%"
                            >
                            </el-input>
                            <el-divider></el-divider>
                            <el-text style="margin-left: -65%; font-size: 16px;padding: 2px">搜索过滤</el-text><br>
                            <el-input v-model="filtered" placeholder="请输入在筛选时需要删除的关键词" clearable
                                      style="padding-top: 2%;width: 80%"/>
                            <el-divider></el-divider>
                            <el-button type="warning" size="large" :icon="Search" @click="select">查 询</el-button>
                        </el-aside>
                        <el-main>
                            <el-row style="font-size: 25px; font-weight:bold;font-family: 幼圆,serif; margin-top:-2%; margin-bottom: 5%; padding: 5px; color: rgb(93,92,92)">
                                    律师搜索结果
                            </el-row>
                            <div class="radiusM"
                            v-for="searchResult in nowData"
                            :key="searchResult.id">
                                <el-row style="margin-top: 1%">
                                    <el-col :span="5">
                                        <el-image :src="searchResult.url" style="width: 120px; height: 120px; padding: 10px;"/>
                                    </el-col>
                                    <el-col :span="6" style="margin-top: 3%">
                                        <div style="font-size: 20px; font-weight: bold; font-family: 微软雅黑,serif;">{{searchResult.lawyerName}}</div>
                                    </el-col>
                                    <el-col :span="10" style="margin-top: 3%; margin-left: 40px">
                                        <el-rate
                                            v-model="searchResult.valueEach"
                                            disabled
                                            show-score
                                            text-color="#ff9900"
                                            score-template="{value} 星"
                                        />
                                    </el-col>
                                </el-row>
                                <el-row style="margin-top: -70px; margin-left: 278px">
                                    <el-col :span="5">
                                        <div style="margin-top:-12%; color: #6b6b6b; font-size: small; padding-bottom: 2px; margin-left: -240px">{{searchResult.phoneNumber}}</div>
                                    </el-col>
                                    <el-col :span="5">
                                        <el-button style=" margin-top: -40%" type="danger" @click="detail(searchResult.id)">查看律师信息</el-button>
                                    </el-col>
                                    <el-col :span="5">
                                        <el-button type="warning" style="margin-top: -40%; margin-left: 100%" @click="score(searchResult.ProfileUrl)">用户评分</el-button>
                                    </el-col>
                                </el-row>
                                <div style="width: 70%; text-align: left; margin-left: 152px; font-size:14px ;color: #626262; padding: 2px">{{searchResult.description}}</div>
                            </div>
                            <el-pagination
                                ::current-page="searchData.current"
                                :page-size="searchData.limit"
                                :total="num"
                                :pager-count="6"
                                style="text-align: center;margin-top: 20px;"
                                layout="jumper, prev, pager, next, total"
                                @current-change="getData"
                           />
                        </el-main>
                    </el-container>
                    <el-dialog title="用户评价" v-model="editFormVisible">
                        <el-form :model="editForm" :rules="rules">
                            <el-form-item label="本次服务的评价" :label-width="formLabelWidth">
                                <el-input
                                    v-model="editForm.describe"
                                    :autosize="{ minRows: 2, maxRows: 4 }"
                                    maxlength="100"
                                    show-word-limit
                                    type="textarea"
                                    autocomplete="off"
                                    placeholder="请输入本次律师服务的感受"
                                >
                                </el-input>
                            </el-form-item>
                            <el-form-item label="本次服务的评分" :label-width="formLabelWidth">
                                <el-input v-model="editForm.score" autocomplete="off"></el-input>
                            </el-form-item>
                        </el-form>
                        <template v-slot:footer>
                            <div class="dialog-footer">
                                <el-button @click="closeDialogForm">取消</el-button>
                                <el-button type="primary" @click="commitScore">确定</el-button>
                            </div>
                        </template>
                    </el-dialog>
                </div>
            </el-main>
        </el-container>
    </div>
</template>

<style scoped>
.input{
    align-items: center;
    background-color: #838a85;
    width: 100%;
    padding-top: 6px;
    padding-bottom: 7px;
}
.radius {
    height: 800px;
    width: 38%;
    border: 1px solid var(--el-border-color);
    border-radius: 2vh;
}
.radiusM {
    margin-top: -2%;
    margin-left: 2%;
    height: 165px;
    width: 97%;
    border: 1px solid var(--el-border-color);
    box-shadow: #3b3b3b;
}
.title{
    background-color: #738080;
    height: 50px;
    font-family: 微软雅黑,serif;
    font-size: 23px;
    color: #cecece;
    font-weight: bold;
    margin-top: 3%;
    margin-left: 20%;
}
.slider-demo-block {
    display: flex;
    width: 86%;
    margin-left: 7%;
    margin-top: 3%;
    align-items: center;
}
.slider-demo-block .el-slider {
    margin-top: 0;
    margin-left: 10px;
}
.slider-demo-block .demonstration {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    line-height: 44px;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-bottom: 0;
}
.slider-demo-block .demonstration + .el-slider {
    flex: 0 0 70%;
}
</style>

<script setup lang="ts">

import {HomeFilled, Search} from "@element-plus/icons-vue";
import {onMounted, reactive, ref} from "vue";
import {provinceAndCityData, codeToText} from 'element-china-area-data'
import HeadPage from "./HeadPage.vue"
import {ElMessage} from "element-plus";
import {RouteParams, useRoute} from "vue-router";
import router from "@/router";
import axios, {post} from 'axios'
const input = ref('')
const inform = '请选择地域：默认全国'
const value = ref(["",""])
let character = ref('');
let userType = ref('-1');   // 用户是否登录
// 换页
let nowData = ref<result[]>([])
const searchData=reactive({
    current:1,
    limit:8
})
function pageQuery(current : number,limit:number){
    // 模仿分页查询，将表格的数据裁切一下
    //     1     2     3
    //下标 0-9 10-19 20-29
    let begin=current*limit-limit
    //这里不减一是因为，slice方法裁切是左闭右开数组
    let end=current*limit
    nowData.value=searchResults.value.slice(begin,end)
    console.log(nowData)

}
function getData(val = 1){
    searchData.current=val
    // 先把数据搞上
    pageQuery(searchData.current,searchData.limit)
}
//
let url = ''
async function commitScore(){
    if(editForm.value.score > 5 || editForm.value.score <= 0){
        ElMessage.warning('请输入0-5之间的评分')
        return
    }
    if(editForm.value.describe === ''){
        ElMessage.warning('请输入评论')
    }
    if(url === ''){
        ElMessage.error('请联系管理员')
        return;
    }
    console.log(url)
    await axios.post('http://localhost:8081/user/postcomment', {
        userId : parseInt(userType.value),
        profileUrl : url,
        score : editForm.value.score,
        content : editForm.value.describe
    }).then(()=>{
        setTimeout(async()=>{
           await getResults();
           ElMessage.success('感谢您的评价')
        }, 1000)
    })
    closeDialogForm()
}

let position = ref('')
let lawyerName = ref('')
let professionalField = ref('')
let serviceArea = ref('')
let lawyerIntroduction = ref('')
let filtered = ref('')
const clear = () => {
    value.value[0] = '';
    value.value[1] = '';
    lawyerName.value = '';
    position.value = '';
    serviceArea.value = '';
    selectedOptions2.value = []
    professionalField.value = '';
    lawyerIntroduction.value = '';
}

let ch = useRoute().params;
onMounted( ()=> {
    character.value = ch['character'].toString()
    userType.value = ch['id'].toString()
    getResults();
});
const score = (Purl : string)=>{
    url = Purl
    console.log(url)
    if(userType.value === '-1'){
        ElMessage.warning('请进行用户登录')
    }
    else{
        openDialogForm()
    }
}

class result{
    public id: number;
    public lawyerName: string;
    public description: string;
    public phoneNumber: string;
    public valueEach: number;
    public url: string;
    public ProfileUrl : string
    public constructor (id: number, lawyerName:string, description:string,
                        phoneNumber: string, valueEach: number, url: string, ProfileUrl : string) {
        this.id = id;
        this.lawyerName = lawyerName;
        this.description = description;
        this.url = url;
        this.phoneNumber = phoneNumber;
        this.valueEach = valueEach;
        this.ProfileUrl = ProfileUrl;
    }
}

const getResults = () =>{
    const queryString = character.value;
    console.log(queryString)
    axios.get('http://localhost:8081/query/fastQuery', {
        params: {
            queryString: queryString,
            uid: userType.value,
        }
    }).then(message=> {
        let data = message.data.data;
        console.log(data)
        deal(data);
        getData();
    }) .catch((error: any) => {
        // 请求失败处理
        console.error(error);
    });
}

const searchResults = ref<result[]>([])
let num = 0

const rules = {
}
const editFormVisible = ref(false);
const formLabelWidth = '150px';

const closeDialogForm = () => {
    editFormVisible.value = false;
};
const openDialogForm = () => {
    editForm.value.score = 5
    editForm.value.describe = ''
    editFormVisible.value = true;
};
const editForm = ref({
    name:'',
    describe:'',
    score:0,
});

let selectedOptions = ref([''])
let location = ref('');
const handleChange = () => {
    for (let i = 0; i < selectedOptions.value.length; i++) {
        location.value += codeToText[(selectedOptions.value[i])];
    }
    console.log(location.value)//打印区域码所对应的属性值即中文地址
}

let selectedOptions2 = ref([''])
const handleChange2 = () => {
    for (let i = 0; i < selectedOptions2.value.length; i++) {
        serviceArea.value += codeToText[(selectedOptions2.value[i])];
    }
    console.log(serviceArea.value)//打印区域码所对应的属性值即中文地址
}

const detail = (id: number) => {
  router.push('/log/' + userType.value + '/inform/' + character.value + '/person/' + id)
}

const back = () =>{
    router.push('/log/' + userType.value)
}
const search = () => {
    if(location.value !== ''){
        input.value = input.value + location.value;
    }
    if(input.value === ''){
        ElMessage.warning("请输入关键字搜索")
    }
    else{
        character.value = input.value
        console.log(character.value)
        getResults();
        input.value = ''
        selectedOptions.value = []
    }
}

function select() {
    if (serviceArea.value && serviceArea.value.length > 0) {
        if (serviceArea.value.includes("北京") || serviceArea.value.includes("上海") || serviceArea.value.includes("天津")) {
            serviceArea.value = serviceArea.value.substring(0, 2);
        }
        serviceArea.value += '全国';
        console.log(serviceArea.value)
    }
    let min = 0
    let max = -1
    if (value.value[0] !== '') {
        min = parseInt(value.value[0])
    }
    if (value.value[1] !== '') {
        max = parseInt(value.value[1])
    }
    axios.post('http://localhost:8081/query/advancedQuery', {
        lawyerName: lawyerName.value,
        position: position.value,
        helpedPeople_gt: min,
        helpedPeople_lt: max,
        serviceArea: serviceArea.value,
        professionalField: professionalField.value,
        lawyerIntroduction: lawyerIntroduction.value,
        filtered: filtered.value
    }).then((message: any) => {
        deal(message.data.data)
        getData()
    })

}
function deal(data : any){
    if(data === null){
        ElMessage.warning("没有搜到更加准确的信息")
        return
    }
    searchResults.value = []
    for(let i = 0; i < data.length; i++){
        let description = data[i].LawyerIntroduction;
        if(description.length > 60){
            description = description.substring(0, 60) + '...';
        }
        if(description.length === 0){
            description = "作为一位富有经验的法律专业人士，"+ data[i].LawyerName +"一直致力于为客户提供卓越的法律服务,在解决复杂法律问题方面拥有卓越的技能和深厚的专业知识。"
        }
        if(data[i].Phone === ''){
            data[i].Phone = '暂无电话信息'
        }
        data[i].Score = data[i].Score.toFixed(2)
        const R = new result(data[i].LawyerDocId, data[i].LawyerName, description, data[i].Phone, data[i].Score, data[i].ImageURL, data[i].ProfileURL);
        searchResults.value.push(R)
    }
    num = searchResults.value.length;
}

</script>
